package com.bruce.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.bruce.model.User;
import com.bruce.service.UserService;
import com.bruce.tool.JWBean;
import com.bruce.tool.MD5Util;
import com.google.code.kaptcha.impl.DefaultKaptcha;

/**
 * 用户管理
 * @author JW
 */
@RestController
@RequestMapping(value = "/manager/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private DefaultKaptcha defaultKaptcha;
	@PostMapping("/add")
	public Map<String, String> addUser( @RequestParam("nickname") String nickname, @RequestParam("pswd") String pswd ){
		String newDate = JWBean.getNowDateByFormat("yyyy-MM-dd HH:mm:ss");
		User user = new User(nickname,  new MD5Util().setPswd(pswd), newDate,  newDate, 1);
		Map<String, String> reMap = new HashMap<String, String>();

		if(JWBean.isEmpty(nickname) || JWBean.isEmpty(pswd) ||( nickname.length() >= 6 && nickname.length()<= 20) || ( pswd.length() >= 6 && pswd.length()<= 20)) {
			reMap.put("status", "0" );
			return reMap;
		}
		
		try {
			reMap.put("status", String.valueOf(userService.insert(user)) );
			reMap.put("userid", String.valueOf(userService.getId(user)) );
		}catch(Exception e) {
			reMap.put("status", "0" );
		}
		return reMap;
	}

	@PostMapping("/list")
	public Object findAllUser(
			@RequestParam(name="pgeNum", required=false, defaultValue="1") int pageNum,
			@RequestParam(name="pageSize", required= false, defaultValue = "10")int pageSize) {
		return userService.selectAll(pageNum,pageSize);

	}

	@PostMapping("/update")
	public Map<String, String> upUser(@RequestParam("id") int id, @RequestParam("pswd") String pswd ){
		User user = new User();
		user.setId(id);
		user.setPswd(new MD5Util().setPswd(pswd));
		Map<String, String> reMap = new HashMap<String, String>();
		try {
			reMap.put("status", String.valueOf(userService.update(user)) );
		}catch(Exception e) {
			reMap.put("status", "0" );
		}
		return reMap;
	}

	/**
	 * 用户登入 需要用验证码版
	 * @param session
	 * @param username
	 * @param pswd
	 * @param verifyCode
	 * @return
	 */
	@PostMapping("/userLogin")
	private  Map<String, String> userLogin(HttpSession session, @RequestParam("nickname")String nickname, @RequestParam("pswd")String pswd, @RequestParam("verifyCode")String verifyCode){
		Map<String, String> reMap = new HashMap<String, String>();
		try {	
			if(!JWBean.isEmpty(nickname) && !JWBean.isEmpty(pswd) && !JWBean.isEmpty(verifyCode) ){
				System.out.println("default kaptcha :"+ session.getAttribute("vrifyCode"));
				
				if(verifyCode.equalsIgnoreCase(session.getAttribute("vrifyCode").toString())){
					User userImpl = userService.getUserInfoByname(nickname);
					if(userImpl  != null){
						if( new MD5Util().setPswd(pswd).equals(userImpl.getPswd())){
							userQuit(session);

							session.setAttribute("LoginUserId",userImpl.getId());
							session.setAttribute("LoginUserName",userImpl.getNickname());

							userService.setLastLoginTime(userImpl);

							reMap.put("status", "1");
							reMap.put("LoginUserName", userImpl.getNickname());
						}else {
							reMap.put("status", "2");
							reMap.put("info", "密码出错");
						}
					}else{
						reMap.put("status", "3");
						reMap.put("info", "账号不存在");
					}
				}else{
					reMap.put("status", "4");
					reMap.put("info", "验证码不匹配");
				}
			}

		}catch (Exception e){
			e.printStackTrace();
			reMap.put("status", "5");
			reMap.put("info", "验证码无效");
		}
		
		return reMap;
	}

	/**
	 * 用户登入 不需要验证码版
	 * @param session
	 * @param username
	 * @param pswd
	 * @param verifyCode
	 * @return
	 */
	@PostMapping("/userLoginDef")
	private  Map<String, String> userLogin(HttpSession session, @RequestParam("nickname")String nickname, @RequestParam("pswd")String pswd){
		Map<String, String> reMap = new HashMap<String, String>();
		try {
			if(!JWBean.isEmpty(nickname) && !JWBean.isEmpty(pswd)  ){

				User userImpl = userService.getUserInfoByname(nickname);
				if(userImpl  != null){
					if( new MD5Util().setPswd(pswd).equals(userImpl.getPswd())){
						userQuit(session);
						session.setAttribute("LoginUserId",userImpl.getId());
						session.setAttribute("LoginUserName",userImpl.getNickname());

						userService.setLastLoginTime(userImpl);

						reMap.put("status", "1");
						reMap.put("LoginUserName", userImpl.getNickname());
					}else {
						reMap.put("status", "2");
						reMap.put("info", "密码出错");
					}
				}else{
					reMap.put("status", "3");
					reMap.put("info", "账号不存在");
				}
			}else {
				reMap.put("status", "5");
				reMap.put("info", "输入内容无效");
			}

		}catch (Exception e){
			reMap.put("status", "5");
			reMap.put("info", "输入内容无效");
		}
		return reMap;
	}
	@PostMapping("/userQuit")
	private  ModelAndView userQuit(HttpSession session){
//		Map<String, String> reMap = new HashMap<String, String>();
//		try {
			session.removeAttribute("LoginUserId");
			session.removeAttribute("LoginUserName");
//			reMap.put("status", "1");
//		}catch (Exception e){
//			e.printStackTrace();
//			reMap.put("status", "0");
//		}
			
			ModelAndView vm = new ModelAndView("/view/ManagePage/login.html");
		return vm;
	}
	@GetMapping("/defaultKaptcha")
	private void defaultKaptcha(HttpSession session,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{
		byte[] captchaChallengeAsJpeg = null;
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

		long VrifyCodeTime = System.currentTimeMillis();
		Object lastVrifyCodeTime = session.getAttribute("vrifyCodeTime");
		if(lastVrifyCodeTime != null && !JWBean.isEmpty(lastVrifyCodeTime.toString()) ){
			if((VrifyCodeTime - Long.valueOf(lastVrifyCodeTime.toString()))<1000) {//1秒内刷新不算,防止恶意攻击
				return ;
			}
		}
		try {
			//生产验证码字符串并保存到session中
			String createText = defaultKaptcha.createText();
			System.out.println("default kaptcha :"+ createText);
			session.setAttribute("vrifyCode", createText);
			session.setAttribute("vrifyCodeTime", VrifyCodeTime);
			//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = defaultKaptcha.createImage(createText);
			ImageIO.write(challenge, "jpg", jpegOutputStream);
		} catch (IllegalArgumentException e) {
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		//定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream =
				httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}

}
